package logger

import (
	"os"
	"path"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var (
	dir = "log" //日志存放的目录
)

func Init(logDir string, debugSql bool) {
	dir = logDir
	initAppLogger()
	initGinLogger()
	initGormLogger(debugSql)
}

var Log *zap.Logger

func initAppLogger() {
	encoder := GetEncoder()
	allWriteSyncer := GetWriteSyncer(path.Join(dir, "app_all.log"))
	infoWriteSyncer := GetWriteSyncer(path.Join(dir, "app_info.log"))
	errorWriteSyncer := GetWriteSyncer(path.Join(dir, "app_error.log"))
	levelEnabler := zapcore.DebugLevel
	consoleEncoder := GetConsoleEncoder()

	// // 级别
	// pAll := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
	// 	if isDebug {
	// 		return lev >= zap.DebugLevel
	// 	}

	// 	return lev >= zap.InfoLevel
	// })

	// 记录大于错误等级的所有数据
	pErrors := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev >= zap.ErrorLevel
	})

	// 等于Info的数据使用
	pInfo := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev == zap.InfoLevel
	})

	newCore := zapcore.NewTee(
		zapcore.NewCore(encoder, allWriteSyncer, levelEnabler),
		zapcore.NewCore(encoder, infoWriteSyncer, pInfo),
		zapcore.NewCore(encoder, errorWriteSyncer, pErrors),                          // 写入文件
		zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel), // 写入控制台
	)
	Log = zap.New(newCore, zap.AddCaller())
	zap.ReplaceGlobals(Log)
}

func Debug(msg string, fields ...zapcore.Field) {
	zap.L().Debug(msg, fields...)
}

func Info(msg string, fields ...zapcore.Field) {
	zap.L().Info(msg, fields...)
}

func Warn(msg string, fields ...zapcore.Field) {
	zap.L().Warn(msg, fields...)
}

func Error(msg string, fields ...zapcore.Field) {
	zap.L().Error(msg, fields...)
}

func Panic(msg string, fields ...zapcore.Field) {
	zap.L().Panic(msg, fields...)
}

func Fatal(msg string, fields ...zapcore.Field) {
	zap.L().Fatal(msg, fields...)
}

func Debugf(format string, args ...interface{}) {
	zap.L().Sugar().Debugf(format, args...)
}

func Infof(format string, args ...interface{}) {
	zap.L().Sugar().Infof(format, args...)
}

func Warnf(format string, args ...interface{}) {
	zap.L().Sugar().Warnf(format, args...)
}

func Errorf(format string, args ...interface{}) {
	zap.L().Sugar().Errorf(format, args...)
}

func Panicf(format string, args ...interface{}) {
	zap.L().Sugar().Panicf(format, args...)
}

func Fatalf(format string, args ...interface{}) {
	zap.L().Sugar().Fatalf(format, args...)
}
